<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <!-- <el-form-item label="礼品图片" prop="giftImages">
        <el-input
          v-model="queryParams.giftImages"
          placeholder="请输入礼品图片"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="礼品名称" prop="giftName">
        <el-input
          v-model="queryParams.giftName"
          placeholder="请输入礼品名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="礼品积分" prop="giftIntegral">
        <el-input
          v-model="queryParams.giftIntegral"
          placeholder="请输入礼品积分"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['brandgifts:brandgifts:add']"
        >新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['brandgifts:brandgifts:edit']"
        >修改</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['brandgifts:brandgifts:remove']"
        >删除</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['brandgifts:brandgifts:export']"
        >导出</el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="brandgiftsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="id" align="center" prop="id" /> -->
      <el-table-column label="序号" type="index" :index="(queryParams.pageNum-1)*10+1" />
      <el-table-column label="礼品名称" align="center" prop="giftName" />
      <el-table-column label="礼品图片" align="center">
          <template slot-scope="scope">
            <el-image
              style="width: 50px; height: 50px"
              :src="scope.row.giftImages"
              fit="cover"
            ></el-image>
          </template>
      </el-table-column>
      <el-table-column label="礼品积分" align="center" prop="giftIntegral" />
      <el-table-column label="库存" align="center" prop="giftNumber" />
      <el-table-column label="开始时间" align="center" prop="activityStartTime" />
      <el-table-column label="结束时间" align="center" prop="activityEndTime" />
      <el-table-column label="创建时间" align="center" prop="createTime" />
      <el-table-column label="创建人" align="center" prop="createBy" />
      <el-table-column label="修改人" align="center" prop="updateBy" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['brandgifts:brandgifts:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['brandgifts:brandgifts:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改品牌会员卡礼品对话框 -->
    <el-dialog :close-on-click-modal="false" v-loading.fullscreen="loading" :title="title" :visible.sync="open" width="80vw" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <!-- <el-form-item label="逻辑删除" prop="isDelete">
          <el-input v-model="form.isDelete" placeholder="请输入逻辑删除" />
        </el-form-item> -->
        <el-form-item label="礼品名称" prop="giftName">
          <el-input v-model="form.giftName" placeholder="请输入礼品名称" />
        </el-form-item>
        <el-form-item label="礼品图片" prop="giftImages"  :class="form.giftImages?'upHide':''">
          <!-- <el-input v-model="form.giftImages" placeholder="请输入礼品图片" /> -->
          <el-upload
            ref="upload"
            :action="$uploadImage"
            list-type="picture-card"
            :on-success="uploadSuccess"
            :on-remove="removeImage"
            :file-list="imageList"
            :headers="headers"
            name="fileList"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        
        <el-form-item label="礼品积分" prop="giftIntegral">
          <el-input v-model="form.giftIntegral" placeholder="请输入礼品积分" @input="form.giftIntegral = form.giftIntegral.replace(/[^\.\d]/g,'')"/>
        </el-form-item>
        <el-form-item label="库存" prop="giftNumber">
          <el-input v-model="form.giftNumber" placeholder="请输入礼品库存" @input="form.giftNumber = form.giftNumber.replace(/[^\.\d]/g,'')"/>
        </el-form-item>
        <el-form-item label="详情" prop="giftDetails">
          <quill-editor ref="QuillEditor" v-model="form.giftDetails" :options="editorOption" 
style="width:400px;height: 300px; margin-bottom: 10px"></quill-editor>
          <div style="height:30px"></div>
          <!-- <el-input v-model="form.giftDetails" type="textarea" placeholder="请输入内容" /> -->
        </el-form-item>
        <el-form-item label="开始时间" prop="activityStartTime">
        <el-date-picker clearable size="small"
          v-model="form.activityStartTime"
          type="datetime"
          value-format="yyyy-MM-dd HH:mm:ss"
          placeholder="选择开始时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="结束时间" prop="activityEndTime">
        <el-date-picker clearable size="small"
          v-model="form.activityEndTime"
          type="datetime"
          value-format="yyyy-MM-dd HH:mm:ss"
          placeholder="选择结束时间">
        </el-date-picker>
      </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-upload
      style="display:none"
      :show-upload-list="false"
      :on-success="handleSuccess"
      multiple
      :action="$uploadImage"
      :headers="headers"
            name="fileList"
      class="upImage"
      >
      <el-button icon="ios-cloud-upload-outline" ></el-button>
    </el-upload>
  </div>
</template>

<script>
import { listBrandgifts, getBrandgifts, delBrandgifts, addBrandgifts, updateBrandgifts, exportBrandgifts } from "@/api/brandgifts/brandgifts";
import { getToken } from '@/utils/auth'
// 工具栏配置
    const toolbarOptions = [
      ['bold', 'italic', 'underline', 'strike'],        // toggled buttons
      // ['blockquote', 'code-block'],
    
      [{'header': 1}, {'header': 2}],               // custom button values
      // [{'list': 'ordered'}, {'list': 'bullet'}],
      // [{'script': 'sub'}, {'script': 'super'}],      // superscript/subscript
      // [{'indent': '-1'}, {'indent': '+1'}],          // outdent/indent
      // [{'direction': 'rtl'}],                         // text direction
    
      // [{'size': ['small', false, 'large', 'huge']}],  // custom dropdown
      // [{'header': [1, 2, 3, 4, 5, 6, false]}],
    
      [{'color': []}, {'background': []}],          // dropdown with defaults from theme
      // [{'font': []}],
      // [{'align': []}],
      ['link', 'image', /*'video'*/],
      // ['clean']                                         // remove formatting button
    ]
export default {
  name: "Brandgifts",
  components: {
  },
  data() {
    return {
      editorOption: {                
            modules: {
                toolbar: {
                    container: toolbarOptions,  // 工具栏
                    handlers: {
                        'image': function (value) {
                            if (value) {
                                // 调用iview图片上传
                                document.querySelector('.upImage .el-button').click()
                            } else {
                                this.quill.format('image', false);
                            }
                        }
                    }
                }
            }
        },
      imageList:[],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 品牌会员卡礼品表格数据
      brandgiftsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        giftImages: null,
        giftName: null,
        giftIntegral: null,
        giftDetails: null
      },
      // 表单参数
      form: {
        
      },
      // 表单校验
      rules: {
        giftName:[
          {required:true,message:'请填写礼品名称',trigger: 'change'}
        ],
        giftImages:[
          {required:true,message:'请选择礼品图片',trigger: 'change'}
        ],
        giftIntegral:[
          {required:true,message:'请填写礼品积分',trigger: 'change'}
        ],
        giftNumber:[
          {required:true,message:'请填写礼品库存',trigger: 'change'}
        ],
        activityStartTime:[
          {required:true,message:'请选择开始时间',trigger: 'change'}
        ],
        activityEndTime:[
          {required:true,message:'请选择结束时间',trigger: 'change'}
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  computed:{
    headers(){
      return {
        'Authorization':'Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
      }
    }
  },
  methods: {
    handleSuccess (res) {
        // 获取富文本组件实例
        let quill = this.$refs.QuillEditor.quill
        // 如果上传成功
        if (res) {
            // 获取光标所在位置
            let length = quill.getSelection().index;
            // 插入图片，res为服务器返回的图片链接地址
            quill.insertEmbed(length, 'image', res.data[0])
            // 调整光标到最后
            quill.setSelection(length + 1)
        } else {
            // 提示信息，需引入Message
            Message.error('图片插入失败')
        }
    },
    // 删除图片
    removeImage(){
      this.form.giftImages = ""
    },
    // 上传成功
    uploadSuccess(e){
      console.log(e,'上传成功')
      this.$set(this.form,'giftImages',e.data[0])
      this.$refs.form.validateField(['giftImages'])
    },
    /** 查询品牌会员卡礼品列表 */
    getList() {
      this.loading = true;
      listBrandgifts(this.queryParams).then(response => {
        this.brandgiftsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        isDelete: null,
        giftImages: null,
        giftName: null,
        giftNumber:null,
        activityStartTime:null,
        activityEndTime:null,
        giftIntegral: null,
        giftDetails: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加品牌会员卡礼品";
      this.imageList = []
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getBrandgifts(id).then(response => {
        this.form = response.data;
        this.imageList = [{
          name:'图片',
          url:response.data.giftImages
        }]
        this.open = true;
        this.title = "修改品牌会员卡礼品";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.loading = true
          if (this.form.id != null) {
            updateBrandgifts(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.loading = false
              this.getList();
            });
          } else {
            addBrandgifts(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.loading = false
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除品牌会员卡礼品编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delBrandgifts(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有品牌会员卡礼品数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportBrandgifts(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
    }
  }
};
</script>
<style>
.upHide .el-upload{
  display: none;
}
.ql-snow .ql-editor img{
  width: 100%;
}
</style>
